package cn.gailvlun.gll.presentation.chat;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.chatkit.dialog.DialogList;
import cn.gailvlun.gll.chatkit.dialog.DialogListAdapter;
import cn.gailvlun.gll.chatkit.dialog.NotificationViewModel;
import cn.gailvlun.gll.chatlib.ChatClient2;
import cn.gailvlun.gll.chatlib.bean.SystemNotification;
import cn.gailvlun.gll.chatlib.dialog.Dialog;
import cn.gailvlun.gll.chatlib.event.ChatStatusEvent;
import cn.gailvlun.gll.databinding.ActivityDialogListBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.apartment.room.GetRoomDetailRes;
import cn.gailvlun.gll.net.base.friend.FriendNotification;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.main.DialogListViewModel;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.LogUtil;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import cn.gailvlun.gll.widget.statelayout.State;
import io.reactivex.functions.Consumer;
import io.realm.RealmResults;
import kotlin.Triple;

import static cn.gailvlun.gll.chatlib.ChatClient2.CONNECTING;
import static cn.gailvlun.gll.chatlib.ChatClient2.NOT_CONNECTED;



public class DialogListActivity extends BaseActivity {

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, DialogListActivity.class);
        context.startActivity(intent);
    }

    public static void openFromNotification(Context context) {
        Intent intent = new Intent(context, DialogListActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private ActivityDialogListBinding mBinding;
    private DialogListAdapter mAdapter;
    private DialogListViewModel mViewModel;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_dialog_list);

        mAdapter = new DialogListAdapter(mContext);
        mBinding.dialogList.setDialogAdapter(mAdapter);

        mBinding.stateLayout.show(State.EMPTY);

        mViewModel = ViewModelProviders.of(this).get(DialogListViewModel.class);
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();

            }
        });
        mBinding.nbv.setOnMenuClickListener2(new NavigationBarView.OnMenuClickListener2() {
            @Override
            public void onMenuClick(NavigationBarView nb, int position) {
                if (position == 0) {
                    FriendListActivity.openActivity(mContext);
                } else {
                    CreateGroupActivity.Companion.openActivity(mContext);
                }
            }
        });

        mBinding.dialogList.setOnDialogClickListener(new DialogList.OnDialogClickListener() {
            @Override
            public void onSystemNotificationClick() {
                SystemNotificationActivity.openActivity(mContext);
            }

            @Override
            public void onFriendNotificationClick() {
                FriendNotificationActivity.openActivity(mContext);
            }

            @Override
            public void onDialogClick(final Dialog dialog) {
                switch (dialog.getMessage().getType()) {
                    default: {
                        if (dialog.isRoom()) {
                            
                            if (mViewModel.isHaveMember(dialog.getUserOrRoomId())) {
                                ChatActivity.openActivity(mContext, dialog.getId());
                            } else {
                                final android.app.Dialog md = DialogUtil.showIndeterminate(mContext);
                                HttpMethods.getRoomService()
                                        .getRoomDetail(dialog.getUserOrRoomId())
                                        .compose(RxUtil.<GetRoomDetailRes>applyScheduler())
                                        .compose(DialogListActivity.this.<GetRoomDetailRes>bindToLifecycle())
                                        .subscribe(new HttpSubscriber<GetRoomDetailRes>() {
                                            @Override
                                            protected void onSuccess(GetRoomDetailRes response) {
                                                mViewModel.saveMyMember(response.getMember());
                                                ChatActivity.openActivity(mContext, dialog.getId());
                                            }

                                            @Override
                                            protected void onFailure(String errMsg, @Nullable GetRoomDetailRes response, int code) {
                                                DialogUtil.showError(mContext, "无法获取当前房间的信息");
                                            }

                                            @Override
                                            protected void onFinish() {
                                                md.dismiss();
                                                super.onFinish();
                                            }
                                        });
                            }
                        } else {
                            ChatActivity.openActivity(mContext, dialog.getId());
                        }
                        break;
                    }
                }
            }
        });
    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        mViewModel.getDialogObservable()
                .subscribe(new Consumer<Triple<RealmResults<SystemNotification>, RealmResults<FriendNotification>, RealmResults<Dialog>>>() {
                    @Override
                    public void accept(Triple<RealmResults<SystemNotification>, RealmResults<FriendNotification>, RealmResults<Dialog>> triple) throws Exception {
                        if (triple.getFirst().size() + triple.getSecond().size() + triple.getThird().size() == 0) {
                            mBinding.stateLayout.show(State.EMPTY);
                        } else {
                            mBinding.stateLayout.show(State.CONTENT);
                            mAdapter.clear();
                            if (triple.getFirst().size() != 0) {
                                mAdapter.add(NotificationViewModel.Companion.transform(triple.getFirst().get(0)), DialogListAdapter.SYSTEM_NOTIFICATION);
                            }
                            if (triple.getSecond().size() != 0) {
                                mAdapter.add(NotificationViewModel.Companion.transform(triple.getSecond().get(0)), DialogListAdapter.FRIEND_NOTIFICATION);
                            }
                            if (triple.getThird().size() != 0) {
                                mAdapter.addAll(triple.getThird(), DialogListAdapter.DIALOG);
                            }
                        }
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStatusEvent(ChatStatusEvent event) {
        updateStatus(event.status);
    }

    
    private void updateStatus(@ChatClient2.Status int status) {
        mBinding.setChatStatus(status);
    }

    @Override
    protected void onStart() {

        updateStatus(ChatClient2.getInstance().getStatus());

        super.onStart();
    }

    public static class Util {
        public static int getStatusVisibility(@ChatClient2.Status Integer status) {
            if (status == null) {
                return View.GONE;
            }
            switch (status) {
                case NOT_CONNECTED: {
                    return View.VISIBLE;
                }
                case CONNECTING: {
                    return View.VISIBLE;
                }
                default: {
                    return View.GONE;
                }
            }
        }

        public static String getStatusText(@ChatClient2.Status Integer status) {
            if (status == null) {
                return null;
            }
            switch (status) {
                case NOT_CONNECTED: {
                    return "当前网络不可用，请检查你的网络设置";
                }
                case CONNECTING: {
                    return "连接中";
                }
                default: {
                    return null;
                }
            }
        }
    }
}
